package com.example.myapplication8.service

import android.app.Service
import android.content.Intent
import android.graphics.PixelFormat
import android.os.Build
import android.os.IBinder
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.widget.Button
import android.widget.Toast
import com.example.myapplication8.R

class FloatingWindowService : Service() {
    private var windowManager: WindowManager? = null
    private var floatView: View? = null
    private var isShowing = true
    private lateinit var params: WindowManager.LayoutParams

    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        try {
            Log.d(TAG, "开始创建悬浮窗服务")
            showFloatingWindow()
        } catch (e: Exception) {
            Log.e(TAG, "创建悬浮窗服务失败: ${e.message}")
            e.printStackTrace()
            stopSelf()
        }
    }

    private fun showFloatingWindow() {
        try {
            // 获取WindowManager服务
            windowManager = getSystemService(WINDOW_SERVICE) as WindowManager
            Log.d(TAG, "获取WindowManager成功")

            // 设置悬浮窗布局参数
            params = WindowManager.LayoutParams().apply {
                type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
                } else {
                    WindowManager.LayoutParams.TYPE_PHONE
                }
                format = PixelFormat.TRANSLUCENT
                flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                width = WindowManager.LayoutParams.WRAP_CONTENT
                height = WindowManager.LayoutParams.WRAP_CONTENT
                gravity = Gravity.TOP or Gravity.START
                
                // 设置初始位置在屏幕右侧中间
                val displayMetrics = resources.displayMetrics
                x = displayMetrics.widthPixels - 200  // 调整初始位置，避免太靠边
                y = displayMetrics.heightPixels / 3   // 调整初始位置到屏幕上方1/3处
            }
            Log.d(TAG, "悬浮窗参数设置完成")

            // 加载悬浮窗布局
            try {
                floatView = LayoutInflater.from(this).inflate(R.layout.float_window, null)
                Log.d(TAG, "悬浮窗布局加载成功")
            } catch (e: Exception) {
                Log.e(TAG, "悬浮窗布局加载失败: ${e.message}")
                throw e
            }

            // 设置按钮点击事件
            setupButtons()
            
            // 设置拖动功能
            setupDragging()

            // 添加悬浮窗到窗口
            try {
                windowManager?.addView(floatView, params)
                Log.d(TAG, "悬浮窗添加到窗口成功")
                Toast.makeText(this, "悬浮窗已启动", Toast.LENGTH_SHORT).show()
            } catch (e: Exception) {
                Log.e(TAG, "添加悬浮窗到窗口失败: ${e.message}")
                throw e
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "显示悬浮窗失败: ${e.message}")
            e.printStackTrace()
            Toast.makeText(this, "悬浮窗启动失败", Toast.LENGTH_SHORT).show()
            stopSelf()
        }
    }

    private fun setupButtons() {
        try {
            // 停止按钮
            val stopButton = floatView?.findViewById<Button>(R.id.btn_stop)
            if (stopButton == null) {
                Log.e(TAG, "未找到停止按钮")
                throw IllegalStateException("停止按钮未找到")
            }
            
            stopButton.setOnClickListener {
                Log.d(TAG, "点击了停止按钮")
                try {
                    stopSelf()
                    Toast.makeText(this, "服务已停止", Toast.LENGTH_SHORT).show()
                } catch (e: Exception) {
                    Log.e(TAG, "停止服务失败: ${e.message}")
                }
            }

            // 隐藏按钮
            val hideButton = floatView?.findViewById<Button>(R.id.btn_hide)
            if (hideButton == null) {
                Log.e(TAG, "未找到隐藏按钮")
                throw IllegalStateException("隐藏按钮未找到")
            }
            
            hideButton.setOnClickListener {
                Log.d(TAG, "点击了隐藏按钮")
                try {
                    if (isShowing) {
                        windowManager?.removeView(floatView)
                        Toast.makeText(this, "悬浮窗已隐藏", Toast.LENGTH_SHORT).show()
                    } else {
                        windowManager?.addView(floatView, params)
                        Toast.makeText(this, "悬浮窗已显示", Toast.LENGTH_SHORT).show()
                    }
                    isShowing = !isShowing
                } catch (e: Exception) {
                    Log.e(TAG, "切换悬浮窗显示状态失败: ${e.message}")
                }
            }
            
            Log.d(TAG, "按钮设置完成")
        } catch (e: Exception) {
            Log.e(TAG, "设置按钮失败: ${e.message}")
            throw e
        }
    }

    private fun setupDragging() {
        try {
            var initialX: Int = 0
            var initialY: Int = 0
            var initialTouchX: Float = 0f
            var initialTouchY: Float = 0f
            var isDragging = false
            var startClickTime: Long = 0

            floatView?.setOnTouchListener { _, event ->
                try {
                    when (event.action) {
                        MotionEvent.ACTION_DOWN -> {
                            initialX = params.x
                            initialY = params.y
                            initialTouchX = event.rawX
                            initialTouchY = event.rawY
                            startClickTime = System.currentTimeMillis()
                            isDragging = false
                            true
                        }
                        MotionEvent.ACTION_MOVE -> {
                            val deltaX = (event.rawX - initialTouchX).toInt()
                            val deltaY = (event.rawY - initialTouchY).toInt()
                            
                            if (Math.abs(deltaX) > 5 || Math.abs(deltaY) > 5) {
                                isDragging = true
                            }
                            
                            if (isDragging) {
                                params.x = initialX + deltaX
                                params.y = initialY + deltaY
                                
                                val displayMetrics = resources.displayMetrics
                                params.x = params.x.coerceIn(0, displayMetrics.widthPixels - (floatView?.width ?: 0))
                                params.y = params.y.coerceIn(0, displayMetrics.heightPixels - (floatView?.height ?: 0))
                                
                                try {
                                    windowManager?.updateViewLayout(floatView, params)
                                } catch (e: Exception) {
                                    Log.e(TAG, "更新悬浮窗位置失败: ${e.message}")
                                }
                            }
                            true
                        }
                        MotionEvent.ACTION_UP -> {
                            if (!isDragging && System.currentTimeMillis() - startClickTime < 200) {
                                floatView?.performClick()
                            }
                            true
                        }
                        else -> false
                    }
                } catch (e: Exception) {
                    Log.e(TAG, "处理触摸事件失败: ${e.message}")
                    false
                }
            }
            
            Log.d(TAG, "拖动功能设置完成")
        } catch (e: Exception) {
            Log.e(TAG, "设置拖动功能失败: ${e.message}")
            throw e
        }
    }

    override fun onDestroy() {
        try {
            Log.d(TAG, "开始销毁悬浮窗服务")
            if (floatView != null && windowManager != null) {
                try {
                    windowManager?.removeView(floatView)
                    Log.d(TAG, "悬浮窗已移除")
                } catch (e: Exception) {
                    Log.e(TAG, "移除悬浮窗失败: ${e.message}")
                }
            }
            super.onDestroy()
        } catch (e: Exception) {
            Log.e(TAG, "销毁服务失败: ${e.message}")
            super.onDestroy()
        }
    }

    companion object {
        private const val TAG = "FloatingWindowService"
    }
} 